package com.liangdemo.web.thread;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 等所有线程执行完成之后在执行主线程
 *
 * @author: LiangErLe
 * @date: 2022/10/19
 **/
public class Test7 {
    public static final int cpuNum = Runtime.getRuntime().availableProcessors();

    public void test() throws InterruptedException {
        //定义线程名字
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().build();

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(cpuNum, cpuNum * 2,
                500, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(1024),
                namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
        List<String> list = new ArrayList<>();
        System.out.println("========================");
        System.out.println("=======开始执行线程池======");
        System.out.println("========================");
        for (int i = 0; i < 1000; i++) {
            threadPoolExecutor.execute(() -> {
                try {
                    String test = getTest();
                    list.add(test);
                    System.out.println(test);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("执行线程.." + Thread.currentThread().getName());
            });
        }
        // 所有任务执行完成且等待队列中也无任务关闭线程池
        threadPoolExecutor.shutdown();
        // 阻塞主线程, 直至线程池关闭
        threadPoolExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        System.out.println("========================");
        System.out.println("=======主线程执行完了======");
        System.out.println("========================");

        System.out.println(list);

    }


    static String getTest() throws InterruptedException {
        return "hello";
    }

    public static void main(String[] args) throws InterruptedException {
        Test7 test7 = new Test7();
        test7.test();
    }
}
